<template>
  <VPage>
    <div class="flex">
      <div class="leftWrap">
        <div class="transition-all duration-[300] h-[100%]" :style="{ width: isShowLeft ? '260px' : 0 }">
          <div class="plan-box">
            <el-date-picker
              v-model="delivery_time"
              type="daterange"
              range-separator="-"
              start-placeholder="Start date"
              end-placeholder="End date"
              class="expect-time"
              value-format="YYYY-MM-DD HH:mm:ss"
            />

            <div v-for="(item, i) in statisticsList" :key="i" class="plan-item">
              <VText :value="`${item.year}年WK${item.week_num}发货计划`" :line="1" />
              <div class="flex items-center date">
                <span class="flex-1">{{ item.start_date }}至{{ item.end_date }}</span>
              </div>
              <el-progress :percentage="item.percent" class="my-[4px]" />
            </div>
          </div>
        </div>

        <span class="isShowLeft" @click="showLeftF">
          <div class="dk-iconfont icon-ArrowLeft" v-show="isShowLeft"></div>
          <div class="dk-iconfont icon-ArrowRight" v-show="!isShowLeft"></div>
        </span>
      </div>

      <VTable ref="tableRef" v-bind="tableOptins" class="rightWrap pmc-table-view">
        <template #high_form="{ form }">
          <!-- class="grid grid-cols-3" -->
          <XForm ref="form" :fieldList="highFieldList" :options="formOption" labelPosition="top" :formData="form" :originOption="originOption" class="w-[720px]"></XForm>
        </template>

        <template #form="{ form }">
          <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption"></XForm>
        </template>

        <template #toolbar_btns>
          <VButton type="primary" @click="handleClick('Notify')">建单通知</VButton>
          <VButton type="primary" @click="handleClick('StatusConfirm')">确认已发货</VButton>
          <VButton type="primary" @click="handleClick('ExceptionDetect')">异常检测</VButton>
          <VButton type="primary" @click="openConfirmInput('add')">变 更</VButton>

          <VButton icon="Upload" class="ml-auto" @click="openConfirmInput('add')">导 出</VButton>
        </template>
      </VTable>
    </div>
    <!-- 弹窗 表单编辑 -->
    <ConfirmInput v-model="batchVisible" v-bind="getCurrentConfirm" @submit="handleConfirmSubmit" />
    <!-- 日志 -->
    <XLog ref="logRef" :api="planSpaLog"></XLog>
  </VPage>
</template>

<script setup lang="jsx" name="shipmentsPlan">
import {
  purchaseShipPlanList,
  purchaseShipPlanStatistics,
  purchaseShipPlanNotify,
  purchaseShipPlanStatusConfirm,
  purchaseShipPlanExceptionDetect,
  purchaseShipPlanExceptionCancel,
  planSpaLog,
} from "@/api/plan"
import { enumOptions, getSupplie, getCountry } from "@/api"
import { ElMessage, ElMessageBox } from "element-plus"

import XForm from "@/components/XForm/index.vue"
// 弹窗 表单编辑
import ConfirmInput from "@/components/ConfirmInput/index.vue"
// 日志
import XLog from "@/components/XLog"
const logRef = ref()
const handleClick = (type) => {
  let api = null
  let title = ""
  switch (type) {
    case "Notify":
      title = "建单通知"
      api = purchaseShipPlanNotify
      break
    case "StatusConfirm":
      title = "确认已发货"
      api = purchaseShipPlanStatusConfirm
      break
    case "ExceptionDetect":
      title = "异常检测"
      api = purchaseShipPlanExceptionDetect
      break
  }

  let checkbox = getSelectRow()
  console.log(1111)
  console.log(checkbox)
  if (!checkbox.length) return
  ElMessageBox.confirm(`${title}选中的 <span class='text-[blue]'>${checkbox.length}</span> 条数据?`, title, {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "error",
    icon: "WarningFilled",
    //
    confirmButtonClass: "pmc-message-confirm-button",
    dangerouslyUseHTMLString: true,
  })
    .then(() => {
      api({ plan_spa_id: checkbox }).then((res) => {
        ElMessage({ type: "success", message: "操作成功" })
        query()
      })
    })
    .catch(() => {
      ElMessage({ type: "info", message: "取消操作" })
    })
}

const isShowLeft = ref(false)
const showLeftF = () => {
  isShowLeft.value = !isShowLeft.value
}
const statisticsList = ref([])
const delivery_time = ref([])
// 获取发货计划
const queryExpectTime = () => {
  purchaseShipPlanStatistics({ expect_delivery_time: delivery_time.value }).then((res) => {
    statisticsList.value = res.data.list
  })
}

const dtlException = (row, item) => {
  let params = {
    purchase_sku_detail_id: row.plan_spa_id,
    exception_info: item,
  }
  purchaseShipPlanExceptionCancel(params).then((res) => {
    ElMessage({ type: "success", message: "操作成功" })
    query()
  })
}

//获取下拉数据
onMounted(async () => {
  getOption()
  queryExpectTime()
})
import { getEnum } from "@/utils/enumUtils"
const getOption = async () => {
  let keys = [...fieldList.value, ...highFieldList.value].map((v) => v.originField).filter(Boolean)
  const data = await getEnum(keys, "enumOptions")
  keys.forEach((key) => {
    originOption.value[key] = data[key]
  })

  const supplier = (await getSupplie())?.data
  originOption.value.supplier = supplier

  const country = (await getCountry())?.data
  originOption.value.country = country
}
// 枚举 数据
const originOption = ref({
  supplier: [],
})

const tableRef = ref()

const data = reactive({
  batchVisible: false,
  getCurrentConfirm: {},
})
const { batchVisible, getCurrentConfirm } = toRefs(data)

const handleConfirmSubmit = (param) => {
  console.log(param)
  getCurrentConfirm.value = {}
  batchVisible.value = false
}
const openConfirmInput = (type, row) => {
  console.log(row)
  let confirmOpt = currentConfirmOpt.remark
  confirmOpt.type = "remark"
  confirmOpt.form = { remark: row.remark }
  getCurrentConfirm.value = confirmOpt
  batchVisible.value = true
}

const currentConfirmOpt = {
  remark: {
    title: "修改备注",
    formOptions: { labelPosition: "right", labelWidth: "140px" },
    fieldOptions: [
      {
        field: "remark",
        label: "备注信息",
        type: "textarea",
        style: { width: "300px" },
        autosize: { minRows: 4, maxRows: 6 },
      },
    ],
    rules: {
      remark: [{ required: true, message: "请输入备注", trigger: "change" }],
    },
  },
}

// //获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  const arr = []
  getCheckboxRecords.map((e) => {
    arr.push(e.plan_spa_id)
  })
  return arr
}

// 查询
const query = () => {
  tableRef?.value.query()
}

const formOption = ref({
  inline: true,
})
const fieldList = ref([
  {
    field: "planRange",
    placeholder: "可批量搜索",
    select: [
      { label: "备货计划单", value: "plan_no" },
      { label: "备货计划名称", value: "plan_name" },
    ],
    selectStyle: { width: "120px" },
    style: { width: "200px" },
  },
  {
    field: "skuRange",
    placeholder: "可批量搜索",
    select: [
      { label: "SKU", value: "sku" },
      { label: "自定义SKU", value: "custom_sku" },
      { label: "ASIN", value: "asin" },
    ],
    style: { width: "200px" },
    selectStyle: { width: "100px" },
  },
  {
    field: "status",
    type: "select",
    options: {
      placeholder: "状态",
      data: [
        { label: "是", value: 1 },
        { label: "否", value: 0 },
      ],
    },
    style: { width: "120px" },
  },
  {
    field: "supplier_id",
    type: "selectV2",
    originField: "supplier",
    options: {
      placeholder: "供应商",
    },
    itemProps: {
      multiple: true,
      collapseTags: true,
      props: {
        label: "supplier_name",
        value: "s_id",
      },
    },
    style: { width: "200px" },
  },
  {
    field: "exception_info",
    type: "select",
    originField: "exception_info",
    // multiple: true,
    // collapseTags: true,

    options: {
      placeholder: "异常原因",
    },
    style: { width: "200px" },
  },
])

const highFieldList = ref([
  {
    // label: "计划类型",
    field: "plan_type",
    type: "select",
    originField: "plan_type",
    options: {
      placeholder: "计划类型",
    },
    style: { width: "320px" },
  },
  {
    // label: "计划部门",
    field: "department_id",
    type: "cascader",
    cascaderType: "department",
    placeholder: "计划部门",
    multiple: true,
    collapseTags: true,
    itemProps: {
      props: {
        emitPath: false,
        multiple: true,
        label: "name",
        value: "id",
        children: "sub",
      },
    },
    style: { width: "320px" },
  },
  {
    // label: "运输类型",
    field: "transport_type",
    type: "select",
    originField: "transport_type",
    options: {
      placeholder: "运输类型",
    },
    style: { width: "320px" },
  },
  {
    // label: "国家",
    field: "country_id",
    type: "select",
    originField: "country",
    options: {
      placeholder: "国家",
    },
    style: { width: "320px" },
  },
  {
    // label: "商品活跃度",
    field: "active",
    type: "select",
    originField: "goods_active",
    options: {
      placeholder: "商品活跃度",
    },
    style: { width: "200px" },
  },
  {
    // label: "商品状态",
    field: "goods_status",
    type: "select",
    originField: "sku_status",
    options: {
      placeholder: "商品状态",
    },
    style: { width: "200px" },
  },
  {
    // label: "货源状态",
    field: "goods_resource_status",
    type: "select",
    originField: "sku_resource_status",
    options: {
      placeholder: "货源状态",
    },
    style: { width: "200px" },
  },
  {
    field: "plan_user_id",
    // label: "计划人员",
    type: "cascader",
    placeholder: "计划人员",
    multiple: true,
    collapseTags: true,
    style: { width: "320px" },
  },
  {
    field: "sale_user_id",
    // label: "运营人员",
    type: "cascader",
    placeholder: "运营人员",
    multiple: true,
    collapseTags: true,
    style: { width: "320px" },
  },
  {
    field: "purchase_user_id",
    // label: "采购人员",
    type: "cascader",
    placeholder: "采购人员",
    multiple: true,
    collapseTags: true,
    style: { width: "320px" },
  },
])

const cellStyle = ({ row, column }) => {
  let height = row.exception_info?.length ? 154 : 106
  let arr = ["purchase_order_info", "external_inspection_info", "purchase_demand_info"]
  let maxNum = Math.max.apply(
    null,
    arr.map((key) => row[key]?.length)
  )
  return {
    height: `${maxNum > 1 ? row.aaaaa.length * 80 : height}px`,
    "padding-bottom": row.exception_info?.length ? "28px" : 0,
  }
}

// //列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      // fee_type: "",
      planRange: { type: "plan_no", value: "" },
      skuRange: { type: "sku", value: "" },

      // orderData: { type: "orderData1", value: "" },
      // timeData: { type: "timeData", value: "" },
      // skuData: { type: "skuData", value: "" },
    },
  },
  cellStyle: cellStyle,
  // rowConfig: { height: "auto" },
  // rowConfig: { height: "160" },
  // text-green
  columns: [
    { type: "checkbox", fixed: "left", width: 40 },
    {
      title: "备货计划信息",
      width: 270,
      slots: {
        default: ({ row }) => (
          <div>
            <VText value={row.purchase_demand_no} line={1} type="link" />
            <VText title="名称" value={row.plan_name} line={1} />
            <VText title="类型" value={row.plan_type_text} line={1} />
            <VText title="部门" value={row.planning_department} line={1} />
            <VText title="预计发货" value={row.estimated_shipment_date} line={1} class="text-red" />
            {row?.exception_info?.length ? (
              <div class="exception-row flex ">
                {row?.exception_info?.map((item) => (
                  <div class="exception-item flex items-center">
                    {item}
                    <div class="dk-iconfont icon-DeleteFilled cursor-pointer " onClick={() => dtlException(row, item)} />
                  </div>
                ))}
              </div>
            ) : (
              ""
            )}
          </div>
        ),
      },
    },

    {
      title: "图片",
      width: 120,
      slots: {
        default: ({ row }) => <el-image class="image w-[80px] h-[80px]" src={row.sku_attr_img} />,
      },
    },
    {
      title: "商品信息",
      width: 240,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <div>
                <VText value={row.status_text} line={1} type="link" />
              </div>
              <el-divider direction="vertical" />
              <VText title="SKU" value={row.sku} line={1} type="link" />
            </div>

            <VText title="自定义" value={row.custom_sku} line={1} />
            <VText title="ASIN" value={row.asin} line={1} />
            <div class="grid grid-cols-2">
              <span class="flex-1">
                <VText title="国家" value={row.site_code} line={1} />
              </span>
              <VText title="活跃度" value={row.is_new == 1 ? "新品" : "非新品"} line={1} class={[row.is_new == 1 ? "text-green" : ""]} />
            </div>
          </div>
        ),
      },
    },
    {
      title: "商品名称",
      width: 240,
      field: "sku_title",
      line: 3,
    },
    {
      title: "数量",
      width: 100,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="计划" value={row.stocking_quantity} line={1} />
            <VText title="已发货" value={row.ship_quantity} line={1} />
          </div>
        ),
      },
    },
    {
      title: "预计发货时间",
      width: 110,
      slots: {
        default: ({ row }) => (
          <div>
            <el-select v-model={row.transportation_type} placeholder="请选择">
              {originOption.value.transport_type.map((d) => (
                <el-option label={d.label} value={d.value} />
              ))}
            </el-select>
            <VText title="运输天数" value={row.transportation_days} line={1} />
          </div>
        ),
      },
    },
    {
      title: "人员信息",
      width: 200,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="计划" value={row.plan_user_name} line={1} />
            <VText title="采购" value={row.purchase_user_name} line={1} />
            <VText title="运营" value={row.sale_user_name} line={1} />
            <VText title="部门" value={row.department_name} line={1} />
          </div>
        ),
      },
    },
    {
      title: "采购信息",
      width: 220,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <div>
                <VText title="采购价" value={row?.purchase_info?.purchase_price} line={1} />
              </div>

              <el-divider direction="vertical" />
              <VText value={`${row?.purchase_info?.batch_num || "-"}起批`} line={1} />
            </div>

            <VText title="采购天数" value={row?.purchase_info?.purchase_days} line={1} />
            <VText title="单箱数量" value={row?.purchase_info?.fcl_num} line={1} />
            <VText title="供应商" value={row?.purchase_info?.supplier_name} line={1} />
          </div>
        ),
      },
    },
    {
      title: "发货信息",
      width: 220,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="整箱数量" value={row?.shipped_info?.fcl_multi} line={1} />
            <VText title="整箱尺寸/cm" value={row?.shipped_info?.fcl_size} line={1} />
            <VText title="单箱重量/kg" value={row?.shipped_info?.fcl_weight} line={1} />
            <VText title="总重量/kg" value={row?.shipped_info?.total_weight} line={1} />
          </div>
        ),
      },
    },
    {
      title: "采购单信息",
      width: 220,
      // fixed: "left",
      slots: {
        default: ({ row }) => (
          <div>
            {row?.purchase_order_info?.map((d) => (
              <div class="row-item ">
                <span class="flex items-center">
                  <div>
                    <VText title={d.purchase_status} />
                  </div>
                  <el-divider direction="vertical" />
                  <VText value={d.purchase_no} line={1} />
                </span>
                <VText title="采购数量" value={d.purchase_num} />
                <VText title="预计到货" value={d.purchase_expect_arrive_time} />
              </div>
            ))}
          </div>
        ),
      },
    },
    {
      title: "外验单信息",
      width: 220,
      // fixed: "left",
      slots: {
        default: ({ row }) => (
          <div>
            {row?.external_inspection_info?.map((d) => (
              <div class="row-item">
                <span class="flex items-center">
                  <div>
                    <VText title={d.external_inspection_status} />
                  </div>
                  <el-divider direction="vertical" />
                  <VText value={d.external_inspection_no} line={1} />
                </span>
                <VText title="预计验货时间" value={d.expect_inspection_time} />
              </div>
            ))}
          </div>
        ),
      },
    },
    {
      title: "备库单信息",
      width: 220,
      // fixed: "left",
      slots: {
        default: ({ row }) => (
          <div>
            {row?.purchase_demand_info?.map((d) => (
              <div class="row-item">
                <span class="flex items-center">
                  <div>
                    <VText title={d.purchase_demand_status} />
                  </div>
                  <el-divider direction="vertical" />
                  <VText value={d.purchase_demand_no} line={1} />
                </span>
                <VText title="发货数量" value={d.purchase_demand_shipped_num} />
                <VText title="预计发货" value={d.purchase_demand_delivery_time} />
                <VText title="物流商" value={d.purchase_demand_logistics} />
              </div>
            ))}
          </div>
        ),
      },
    },
    {
      title: "备注信息",
      width: 240,
      slots: {
        default: ({ row }) => (
          <div class="cursor-pointer" onClick={() => openConfirmInput("remark", row)}>
            <svg-icon icon-class="edit_icon" class="text-[#3487ff]" />
            <div>{row.remark}</div>
          </div>
        ),
      },
    },

    {
      title: "操作",
      width: 150,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-button link type="primary">
                创建备库单
              </el-button>

              <el-button link type="primary" onClick={() => logRef?.value.open({ spa_id: row.plan_spa_id })}>
                日志
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let params = {
          ...form,
          page: page.pageNum,
          page_num: page.pageSize,
        }
        console.log(params)
        return purchaseShipPlanList(params)
      },
    },
  },
})
</script>
<style lang="scss" scoped>
.leftWrap {
  position: relative;
  height: calc(100vh - 92px);
  box-shadow: 1px 0px 0px 0px #e6e7e9;
  z-index: 999;
  .isShowLeft {
    border-radius: 4px;
    position: absolute;
    width: 20px;
    height: 40px;
    right: -10px;
    top: calc(50% - 20px);
    line-height: 40px;
    text-align: center;
    z-index: 1002;
    background-color: #ccc;
    box-shadow: 0 0 10px #f0f4fe;
    cursor: pointer;
    .el-icon {
      color: #fff;
    }
  }
  .plan-box {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    .plan-item {
      margin: 8px;
      padding: 8px;
      border: 1px solid #e6e7e9;
      margin-bottom: 8px;
      border-radius: 4px;
      .date {
        font-size: 12px;
        font-weight: 400;
        color: #999999;
      }
    }
    :deep(.expect-time) {
      width: 244px;
      margin: 10px 0 0 8px;
    }
  }
}

.rightWrap {
  flex: 1;
  width: 50%;
  height: calc(100vh - 92px);
  :deep(.vxe-cell) {
    max-height: 100% !important;
  }

  :deep(.vxe-body--row) {
    position: relative;
    .vxe-body--column {
      position: static;
    }
    .exception-row {
      background: #ffe5e5;
      position: absolute;
      height: 24px;
      left: 40px;
      right: 0;
      bottom: 0;
      width: calc(100% - 40px);
      padding: 4px 12px;
      font-size: 12px;
      border-radius: 6px;
      .exception-item {
        background: #e50113;
        color: #fff;
        margin-right: 16px;
        line-height: 16px;
        padding: 0 8px;
        border-radius: 12px;
        .el-icon {
          color: #fff;
        }
      }
    }
  }
  :deep(.row-item) {
    border-radius: 4px;
    border: 1px solid #e6e7e9;
    padding: 4px 8px;
  }
}
</style>
